package bulkyshare.project.de.bulkyshare.activities;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import bulkyshare.project.de.bulkyshare.R;
import bulkyshare.project.de.bulkyshare.container.Bulk;
import bulkyshare.project.de.bulkyshare.container.Contact;
import bulkyshare.project.de.bulkyshare.container.Termin;
import bulkyshare.project.de.bulkyshare.tasks.TaskHandler;
import bulkyshare.project.de.bulkyshare.views.TwoRowedListViewAdapter;

/**
 * @author Alexander Radtke
 * @version 1.0
 *
 * This class shows all the Collection dates, that the currently logged-in user, created.
 * The user can add new dates by clicking on the add symbol in the action bar.
 */
public class MyPickupDates extends Fragment implements AdapterView.OnItemClickListener {
    private List<Termin> termine;
    private ListView listView;
    private TwoRowedListViewAdapter listAdapter;
    private String user_id;

    private TaskHandler taskHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_pickup_dates, container, false);
        setHasOptionsMenu(true);

        Bundle info = this.getArguments();
        if (info != null) {
            user_id = info.getString("user_id");
        }

        termine = new ArrayList<Termin>();

        listView = (ListView) view.findViewById(R.id.my_collection_dates_list);
        listAdapter = new TwoRowedListViewAdapter(getActivity(), termine);
        listView.setAdapter(listAdapter);
        // Load all pickup dates for this user
        getMyPickUpDates(Integer.valueOf(user_id));

        listView.setOnItemClickListener(this);
        registerForContextMenu(listView);
        return view;
    }

    /**
     * Called when the user returns to this View.
     * Happens when a new pickup date was created and needs to be added to the ListView
     */
    @Override
    public void onResume() {
        super.onResume();
        // Refresh MyPickupDates
        termine.clear();
        getMyPickUpDates(Integer.valueOf(user_id));
    }

    /**
     * This class Handles clicks on the ListView items.
     * If you click on one item you will be forwarded to the detail View of the item.
     */
    @Override
    public void onItemClick(AdapterView adapterView, View view, int pos, long id) {
        Log.d("Position: ", Integer.toString(pos));
        // forward to detail View
        Intent detail = new Intent(getActivity(), PickupDateDetail.class);
        detail.putExtra("termin_object", termine.get(pos));
        detail.putExtra("name", getActivity().getActionBar().getTitle());
        startActivity(detail);
    }


    /**
     * Create a ContextMenu with two options one for deleting a pickup date and one for editing it.
     * The ContextMenu will be opened on a long click on a ListView item.
     * @param menu
     * @param view
     * @param menuInfo
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, view, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        // Set Header Title with the date of the item
        menu.setHeaderTitle(termine.get(info.position).getDate());
        String[] values = getResources().getStringArray(R.array.context_menu_items);
        for (int i = 0; i < values.length; i++) {
            // Items will be ordered by i
            menu.add(Menu.NONE, i, i, values[i]);
        }
    }

    /**
     * Handle clicks on the two ContextMenu items and perform actions.
     * @param item
     * @return True when action is done
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            // Edit an item
            case 0:
                Intent edit = new Intent(getActivity(), CreatePickupDate.class);
                edit.putExtra("user_id", user_id);
                edit.putExtra("edit", Boolean.valueOf(true));
                edit.putExtra("edit_termin", termine.get(info.position));
                startActivity(edit);
                return true;
            // Delete an item
            case 1:
                // Open a "are you sure you want to delete this" Dialog
                Log.d("position", new Integer(info.position).toString());
                deleteDialog(info.position);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // inflate the menu for the action bar. Contains a button to add a pickup date
        inflater.inflate(R.menu.my_collection_dates_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_collection_date:
                // Show Add Activity
                Intent intent = new Intent(getActivity(), CreatePickupDate.class);
                intent.putExtra("user_id", user_id);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Get all pickup dates from the database which belong to a specific user.
     * @param profile_id The profile id of the currently logged in user
     */
    private void getMyPickUpDates(int profile_id) {
        try {
            taskHandler = new TaskHandler(getActivity());
            taskHandler.setPara(new int[]{profile_id});
            List<Termin> db = (List<Termin>) taskHandler.execute("getAllTermineByProfile").get();
            for (int i = 0; i < db.size(); i++) {
                termine.add(db.get(i));
                // Load all bulky items that belong to this termin_id
                taskHandler = new TaskHandler(getActivity());
                taskHandler.setPara(new int[]{termine.get(i).getId()});
                ArrayList<Bulk> bulk = (ArrayList<Bulk>) taskHandler.execute("getBulks").get();
                termine.get(i).setBulk(bulk);
                // Load all contacts that belong to this termin_id
                taskHandler = new TaskHandler(getActivity());
                taskHandler.setPara(new int[]{termine.get(i).getId()});
                ArrayList<Contact> contacts = (ArrayList<Contact>) taskHandler.execute("getContacts").get();
                termine.get(i).setContacts(contacts);
            }
            // Redraw the ListView because new elements were added
            listAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This Dialog removes a pickup date from the ListView and the database
     * @param pos The position inside the ListView
     */
    private void deleteDialog(final int pos) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(termine.get(pos).getDate());
        builder.setCancelable(false);
        builder.setMessage(R.string.delete_message);
        builder.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Delete the pickup date from the database
                taskHandler = new TaskHandler(getActivity());
                taskHandler.setPara(new int[]{termine.get(pos).getId()});
                taskHandler.execute("deleteTermin");
                termine.remove(pos);
                listAdapter.notifyDataSetChanged();
                dialogInterface.dismiss();
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
